<script setup lang="ts">
import { ref, onBeforeUnmount, reactive, onMounted, watchEffect, watch } from 'vue'
import { useUserStore } from '../../store/modules/user'
import { sessionStorage } from '../../utils/storage';
import { GetuserInfo } from '../../utils/ipcRequest';
import { useRouter } from "vue-router";
// import { setCookie } from '../../utils/auth'
import { userSiteList } from "../../api/home"
import { Empty } from 'ant-design-vue';
import ContextMenu from '../../components/ContextMenu.vue';
import publishArticle from '../../components/publishArticle.vue'
import fullAutomaticPulish from '../../components/fullAutomaticPulish.vue'
import { userSiteArticleList, articleLists, articleRemove,articleWithdraw, adnewspvtrend, getAppStatistic,getauthorhistory, getNewtotalincome, articlePublishNum, getSquareMissionList } from '../../api/article'
type Key = string | number;
const userStore = useUserStore()
const router = useRouter();
// 去详情页列表
const onDetails = (site_id:any, cookie:any) => {
  console.log('跳转页面了')
  // router.push({path: '/articleList', query: {siteId:16 site_id, cookie: 'BIDUPSID=9783AE509A6A036AAC8B53CCEB41763C; PSTM=1705024699; BDUSS=4weTUteTJSTXhrNUVuc05OZjRXSzk2RzJLNURmS3V1b1BEQWNTQ09CdWlQbkJtSUFBQUFBJCQAAAAAAAAAAAEAAADXtQO4va3j69bTAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKKxSGaisUhmVn; BDUSS_BFESS=4weTUteTJSTXhrNUVuc05OZjRXSzk2RzJLNURmS3V1b1BEQWNTQ09CdWlQbkJtSUFBQUFBJCQAAAAAAAAAAAEAAADXtQO4va3j69bTAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKKxSGaisUhmVn; MAWEBCUID=web_cZszphDSxGIzOqcQhAhfKyaToGOCRAUixLRqECRcQSKibcurXH; BAIDUID=8A2C4E89670246269AB9ACB328B14E8C:FG=1; PHPSESSID=gk1tka5e4pefu58oj0tettr6q3; H_WISE_SIDS_BFESS=110085_633616_633567_638431_638466_638129_638943_638941_638947_638939_639209_638578_639384_639805; H_WISE_SIDS=60278_61027_61737_61780_61890_61986; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; H_PS_PSSID=60278_61027_61737_61780_61890_61953_61956_61986; BAIDUID_BFESS=8A2C4E89670246269AB9ACB328B14E8C:FG=1; BDRCVFR[feWj1Vr5u3D]=I67x6TjHwwYf0; delPer=0; PSINO=2; Hm_lvt_f7b8c775c6c8b6a716a75df506fb72df=1737603066; HMACCOUNT=D50073EF615640A1; __bid_n=1949136ab9495527b2482f; theme=bjh; devStoken=5a8a3cba629a77175c43c7bc704881334fae7ad172b3d51a58ec9c4ddc61e8f2; bjhStoken=410de1773f74b11bd1ec8646165336204fae7ad172b3d51a58ec9c4ddc61e8f2; XFT=0dxdQcZBbBMte+zMHVUcERthzYUDB7Yc1Buaky4h2jE=; RT="z=1&dm=baidu.com&si=e253fc38-c504-414e-ac0d-5afeff908ea5&ss=m68s023n&sl=1&tt=42u&bcn=https%3A%2F%2Ffclog.baidu.com%2Flog%2Fweirwood%3Ftype%3Dperf"; Hm_lpvt_f7b8c775c6c8b6a716a75df506fb72df=1737603096; XFI=8d2caaa0-d93a-11ef-b6f7-0744177964f3; XFCS=7C1D9EF7DBDC64918DC224671E56F6FFD222CF7BCD4216861B9BFBB3997E1A6A; ab_sr=1.0.1_NjMyMDgzMmQ1YzMxZmQ5YzQzNzkzYTM0MGEyNTYwZTUxYzBkZWM3ODZiNTgzY2MyNjQwMzlhNTNiYjA0MGJlZjRiMDYxMmI5MTcwZDdiZDI4ZjRjNjVjMGUzZmUzY2ViZWI1OWZjZWJkYmFmN2MyM2UyYTAzMDQxYmQ0ZmY2OTZlMGQ5MDY0ODViMTMwOGQ4ZmJhZmM0MDdiNGIxZDk3YmZmZWVmOTM2Y2IwMDY0MTI0ZjA3YTZlMTQxNWZjNWM5MDY5MWZhNjRmZGQ3NzE5ZjU1NTc1Y2FkZTk4NWYzYzdjY2Q4MzkwNGE1ZDY5ZjUyYmFlMWNkOWRlNTljZTQ0Yg=='}})
  if(isSeeDetails.value) {
    router.push({path: '/articleList', query: {siteId: site_id, cookie: cookie ? cookie : ''}})
  } else {
    // message.warning('正在下载中');
  }
}

const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
const current = ref<number>(1); // 页数
const pageSize = ref<number>(15)
const total = ref<number>(0); // 总数
const siteList:any = ref([])
const isDefaultCan:any = ref(true) // 默认进入是否执行完列表的所有数据，再执行下载
const onChange = (pageNumber: number) => {
  current.value = pageNumber
  isStop.value = true
  onUserSiteList()
};

// 获取站点信息
const initLoading = ref(false)
const state = reactive<{
  selectedRowKeys: Key[];
  selectedRows: Key[];
  loading: boolean;
  indeterminate: boolean,
  checkAll: boolean,
  refreshLoading:boolean,
  inspectionLoading: boolean
}>({
  selectedRowKeys: [], // Check here to configure the default column
  selectedRows: [],
  loading: false,
  indeterminate: false,
  checkAll: false,
  refreshLoading:false, // 数据刷新加载
  inspectionLoading: false, // 每日巡检
});
const onUserSiteList = () => {
  initLoading.value = true
  isDefaultCan.value = false
  userSiteList({page: current.value}).then((response:any) => {
    const result = response.data
    result.data.data.forEach((item:any) => {
      item.isVisible = false
    })
    if(sessionStorage.get(`site_list_num`)) {
      let site_num = JSON.parse(sessionStorage.get(`site_list_num`))
        // 将 array2 中的 description 赋值到 array1 中
      siteList.value = result.data.data.map(item1 => {
        const item2 = site_num.find(item2 => item2.site_id === item1.site_id);
        if (item2) {
          return { ...item1,isVisible:false, read_amount: item2.read_amount,yesterday_view_count:item2.yesterday_view_count,total_view_count:item2.total_view_count,income:item2.income, publish_num_left: item2.publish_num_left, publish_num_text: item2.publish_num_text, today_publish_num:item2.today_publish_num, pulish_num: item2.pulish_num,activity_list: item2.activity_list, square_mission_List: item2.square_mission_List};
        }
        return item1;
      });
      total.value = result.data.total
      initLoading.value = false
      let monitor = userStore.monitor
      isDefaultCan.value = true
      if(monitor == true && siteList.value.length > 0) {
        isStop.value = false
      } else {
        isStop.value = true
        if (timer.value) {
          clearTimeout(timer.value)
          timer.value = null
        }
        if (timer2.value) {
          clearTimeout(timer2.value)
          timer2.value = null
        }
        if (timer3.value) {
          clearTimeout(timer3.value)
          timer3.value = null
        }
      }
    } else {
      siteList.value = result.data.data
      total.value = result.data.total
      otherGetData(0)
    }
  })
  .catch(err => { console.log('err',err);initLoading.value = false})
}
// 获取文章列表
const timer:any = ref(null)
const timer2:any = ref(null)
const timer3:any = ref(null)
const isStop = ref(false) // 是否停止
const isSeeDetails = ref(false) // 判断是否可以点进列表

// 一键发布
const onPulish = (data: any) => {
    console.log('45345345435',data)
    isStop.value = data.isUpload 
}
// 清除选中的数据
const onClear = () => {
  state.selectedRows = []
  state.selectedRowKeys = []
}
// 刷新列表
const onRefreshList = () => {
  isStop.value = true
  onUserSiteList() // 站点列表
}

// 数据刷新
const onDataRefresh = () => {
  isStop.value = true
  state.refreshLoading = true
  otherGetData(0)
}

const read_site_amount:any = ref([]) // 获取存储的站点数据
// 获取每个账号的数据
const otherGetData = (idx:any) => {
  const executeNext_2 = async (index) => {
    if(index >= siteList.value.length) {
      // siteList.value[idx].list_status = true
      // siteList.value[idx].list_status_reason = '已完成'
      initLoading.value = false
      state.refreshLoading = false
      isDefaultCan.value = true
      let monitor = userStore.monitor
      console.log('5445monitor',monitor,siteList.value)
      for(let i in siteList.value) {    
        let Data = { 
          read_amount: siteList.value[i].read_amount,
          yesterday_view_count: siteList.value[i].yesterday_view_count,
          total_view_count: siteList.value[i].total_view_count,
          income: siteList.value[i].income,
          publish_num_left: siteList.value[i].publish_num_left, // 剩余发布
          publish_num_text: siteList.value[i].publish_num_text, // 剩余发布文字信息
          today_publish_num: siteList.value[i].today_publish_num, // 今日发布
          pulish_num: siteList.value[i].pulish_num, // 文章可发布数
          activity_list: siteList.value[i].activity_list, // 设置列表
          square_mission_List: siteList.value[i].square_mission_List, // 征文任务列表
          site_id: siteList.value[i].site_id
        }
        read_site_amount.value.push(Data)
      }
      sessionStorage.set(`site_list_num`,JSON.stringify(read_site_amount.value))
      if(monitor == true && siteList.value.length > 0) {
          isStop.value = false
      } else {
          isStop.value = true
          if (timer.value) {
            clearTimeout(timer.value)
            timer.value = null
          }
          if (timer2.value) {
            clearTimeout(timer2.value)
            timer2.value = null
          }
          if (timer3.value) {
            clearTimeout(timer3.value)
            timer3.value = null
          }
      }
      return
    }
    const currentItem = siteList.value[index]
    if(currentItem.port_config && currentItem.port_config.cookie) {
      let userInfoObj:any = await GetuserInfo(currentItem.port_config.cookie,currentItem.site_id)
      console.log('设置返回：',userInfoObj)
      let userInfoResult = JSON.parse(userInfoObj)
      if(userInfoResult.success) {
        onAdnewspvtrend(index)
      } else {
        executeNext_2(index + 1)
      }
    }
  }
  executeNext_2(idx)
}
//百家号获取阅读量
const onAdnewspvtrend = (index:any) => {
 // 获取当前日期和时间
 const now = new Date();
  // 获取当天零点的时间戳（毫秒）
  const todayMidnight = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
  // 昨天零点的时间戳（秒）
  const yesterdayMidnight:any = (todayMidnight - 24 * 60 * 60 * 1000) / 1000; // 减去一天的时间（秒）
  // 前天零点的时间戳（秒）
  const dayBeforeYesterdayMidnight = yesterdayMidnight - 24 * 60 * 60 ; // 再减去一天的时间（秒）
  let obj = {
    type: 'ad_income',
    start_date: dayBeforeYesterdayMidnight,
    end_date: yesterdayMidnight,
    // start_date: 1740153600,
    // end_date: 1740240000,
    version: 3
  }
  adnewspvtrend(obj).then((response:any) => {
      const result = response.data.data
      siteList.value[index].read_amount = result
      onAppStatistic(index)
  }).catch(() => {
      onAppStatistic(index)
  })
}
//获取昨日日期
const yesterdayDate = () => {
  const today:any = new Date();
  const yesterday = new Date(today);
  yesterday.setDate(yesterday.getDate() - 1); // 将日期设置为昨天
  const year = yesterday.getFullYear();
  const month = String(yesterday.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，需要+1，并且确保是两位数
  const day = String(yesterday.getDate()).padStart(2, '0'); // 获取日期并确保是两位数
  return `${year}${month}${day}`;
}
// 百家号获取昨日阅读数
const onAppStatistic = (index:any) => {
  let obj = {
    type: 'all',
    is_yesterday: false,
    start_day: yesterdayDate(),
    end_day: yesterdayDate(),
    stat: 0
  }
  const params:any = new URLSearchParams();
  params.append('type','all')
  params.append('is_yesterday',false)
  params.append('start_day',yesterdayDate())
  params.append('end_day',yesterdayDate())
  params.append('stat',0)
  getAppStatistic(obj).then((response:any) => {
      const result = response.data.data
      siteList.value[index].yesterday_view_count = result.yesterday.view_count
      onauthorhistory(index)
  }).catch(() => {
    onauthorhistory(index)
  })
}
// 百家号获取总阅读数
const onauthorhistory = (index:any) => {
  getauthorhistory().then((response:any) => {
      const result = response.data.data
      siteList.value[index].total_view_count = formatNumberToWan(result.total.view_count)
      onIncomeoverviewlist(index)
  }).catch(() => {
    onIncomeoverviewlist(index)
  })
}
// 百家号获取总收益
const onIncomeoverviewlist = (index:any) => {
  getNewtotalincome().then((response:any) => {
      const result = response.data.data
      siteList.value[index].income = result
      onGetSquareMissionList(index)
  }).catch(() => {
      onGetSquareMissionList(index)
  })
}
// 获取征文任务列表
const onGetSquareMissionList = (index:any) => {
  let obj = {
    page_no: 1,
    article_type: 1,
    page_size: 18,
    task_attend: 1,
    task_origin: 'market',
    task_type: -1,
    from: 'pc_edit'
  }
  getSquareMissionList(obj).then((response:any) => {
      const result = response.data.data
      siteList.value[index].square_mission_List = result.list
      getArticlePublishNum(index)
  }).catch(() => {
      getArticlePublishNum(index)
  })
}
const formatNumberToWan = (value) => {
  if (value >= 10000) {
    return (value / 10000).toFixed(2) + '万';
  }
  return value;
}
// 百家号获取剩余发布数
const getArticlePublishNum = (index:any) => {
  articlePublishNum({type: 'news'}).then((response:any) => {
      const result = response.data.data
      siteList.value[index].publish_num_left = result.ability.publish_num_left
      siteList.value[index].publish_num_text = result.ability.publish_num_text
      siteList.value[index].activity_list = result.article.activity_list
      onListPulish(index)
  }).catch(() => {
    onListPulish(index)
  })
}
// 文章列表-获取今日发布数
const onListPulish = (idx:any) => {
  let obj = {
        currentPage: 1,
        pageSize: 15,
        search: '',
        type: 'news',
        collection: 'publish',
        clearBeforeFetch: false
    }
    articleLists(obj).then((response:any) => {
      const result = response.data.data
      let arr2 = result.list.filter((item2:any) => isToday(item2.publish_time))
      console.log('今日发布数',arr2)
      siteList.value[idx].today_publish_num = arr2.length
      let arr = result.list.filter((item2:any) => item2['status'] == 'rejected' || (item2['status'] == 'publish' && item2.audit_msg != '') || (item2['status'] == 'forbidden' && item2.audit_msg != ''))
      // 自动删除审核未通过的文章
      if(arr.length > 0) {
          const executeNext2 = (index) => {
            if(index >= arr.length) {
              setTimeout(() => {
                onListPulish(idx)
              }, 2000)
              return
            }
            if(arr[index]['status'] == 'publish') {
              // 状态已发布-先撤回再删除
              articleWithdraw({article_id: arr[index]['article_id']}).then((response:any) => {
                  const result = response.data
                  console.log('articleRemove',result)
                  articleRemove({article_id: arr[index]['article_id']}).then((response:any) => {
                      console.log(`异步操作: ${ arr[index]['article_id']}`, response);
                      setTimeout(() => {
                        executeNext2(index+1)
                      }, 2000)
                  }).catch(() => {
                    setTimeout(() => {
                      executeNext2(index+1)
                    }, 2000)
                  });
              }).catch(() => {
                setTimeout(() => {
                  executeNext2(index+1)
                }, 2000)
              });
            } else {
              articleRemove({article_id: arr[index]['article_id']}).then((response:any) => {
                  console.log(`异步操作: ${ arr[index]['article_id']}`, response);
                  setTimeout(() => {
                    executeNext2(index+1)
                  }, 2000)
              }).catch(() => {
                setTimeout(() => {
                  executeNext2(index+1)
                }, 3000)
              });
            }
          }
          executeNext2(0)
      } else {
        onArticleList2(idx)
      }
    }).catch(() => {
      onArticleList2(idx)
    })
}
// 获取文章可发布数
const onArticleList2 = (index:any) => {
  const currentItem = siteList.value[index];
  userSiteArticleList({page: 1,limit: 15, siteId: currentItem.site_id}).then((response:any) => {
    const result = response.data.data
    processItems2(result.data, index)
  }).catch(() => {
    otherGetData(index + 1)
  })
}

// 默认获取是否有下载上传
const processItems2 = async (data:any, index:any) => {
  for (let i in data) {
    let path = `images_${data[i].article_id}`; // 从开始到点号位置截取字符串
    const result = await window.electron.ipcRenderer.invoke('list-directory', path); // 等待操作完成
    // console.log(result)
    // 处理结果或更新数组项
    if(Array.isArray(result.imageArr)) {
      if(result.imageArr.length != 0) {
        data[i]['isDownload'] = true
        data[i]['downloadReason'] = '已解压' // 将修改后的对象添加到新数组中
      } else {
        data[i]['isDownload'] = false
        data[i]['downloadReason'] = ''
      }
    } else {
      data[i]['isDownload'] = false
      data[i]['downloadReason'] = ''
    }

    // 获取图片文件
    let pathJson = `images_${data[i].article_id}.json`;
    const resFile = await window.electron.ipcRenderer.invoke('json-directory', pathJson); // 等待操作完成
    // console.log(resFile,'resFile')
    if(resFile.type == 2) {
      let jsonData = JSON.parse(resFile.urlArr)
      data[i]['isUpload'] = true
      data[i]['uploadReason'] = '已上传' // 将修改后的对象添加到新数组中
      data[i]['uploadText'] = '已上传'
      data[i]['imgNum'] = jsonData.data.length
    } else if(resFile.type == 1 && data[i]['is_release'] == 0 && data[i]['status'] == 50 && data[i]['img_status'] == 20 && data[i]['isDownload']) {
      data[i]['isUpload'] = false
      data[i]['uploadReason'] = '' // 将修改后的对象添加到新数组中
      data[i]['uploadText'] = ''
    } else {
      data[i]['isUpload'] = false
      data[i]['uploadReason'] = '' // 将修改后的对象添加到新数组中
      data[i]['uploadText'] = ''
    }
  }
  let resultData = data.filter((item1:any) =>item1.is_release == 0 && item1.status == 50 && item1.img_status == 20 && item1.isDownload && item1.isUpload)
  if(resultData.length > 0){
      siteList.value[index].pulish_num = resultData.length
  } else {
    siteList.value[index].pulish_num = 0
  }
  otherGetData(index + 1)
};
// 判断是否为今天的时间
const isToday =(date) => { 
  // 获取当前日期
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 将时间设置为今天的 00:00:00
  const specifiedTime = new Date(date);
  specifiedTime.setHours(specifiedTime.getHours() + specifiedTime.getTimezoneOffset() / 60); // 调整时区
  // date.setHours(0, 0, 0, 0); // 将给定日期的时间也设置为00:00:00，以便比较日期部分
  // return date.getTime() === today.getTime();
  return specifiedTime.toDateString() === today.toDateString()
}

/**
 *  每日巡检
 */
const dayInspectionData = () => {
  isStop.value = true
  state.inspectionLoading = true
  otherGetData2(0)
}

// 获取每个账号的数据
const otherGetData2 = (idx:any) => {
  const executeNext_2 = async (index) => {
      if(index >= siteList.value.length) {
        state.inspectionLoading = false
        isDefaultCan.value = true
        let monitor = userStore.monitor
        if(monitor == true && siteList.value.length > 0) {
          isStop.value = false
        } else {
          if (timer.value) {
            clearTimeout(timer.value)
            timer.value = null
          }
          if (timer2.value) {
            clearTimeout(timer2.value)
            timer2.value = null
          }
          if (timer3.value) {
            clearTimeout(timer3.value)
            timer3.value = null
          }
        }
        return
      }
      const currentItem = siteList.value[index]
      if(currentItem.port_config && currentItem.port_config.cookie) {
        let userInfoObj:any = await GetuserInfo(currentItem.port_config.cookie,currentItem.site_id)
        console.log('设置返回：',userInfoObj)
        let userInfoResult = JSON.parse(userInfoObj)
        if(userInfoResult.success) {
          onListPulish2(index, 1)
        } else {
            executeNext_2(index + 1)
        }
      }
  }
  executeNext_2(idx)
}
// 文章列表-获取剩余发布数
const onListPulish2 = (idx:any, page:any) => {
  let obj = {
        currentPage: page,
        pageSize: 15,
        search: '',
        type: 'news',
        collection: 'publish',
        clearBeforeFetch: false
    }
    articleLists(obj).then((response:any) => {
      const result = response.data.data
      let arr2 = result.list.filter((item2:any) => isYesterday(item2.publish_time))
      console.log('昨日数据',arr2)
      let arr = arr2.filter((item2:any) => item2['status'] == 'rejected' || (item2['status'] == 'publish' && item2.audit_msg != '') || (item2['status'] == 'forbidden' && item2.audit_msg != '') || item2.rec_amount == 0)
      // 自动删除审核未通过的文章
      if(arr.length > 0) {
          const executeNext2 = (index) => {
            if(index >= arr.length) {
                setTimeout(() => {
                  onListPulish2(idx, 1)
                }, 2000)
              return
            }
            if(arr[index]['status'] == 'publish') {
              // 状态已发布-先撤回再删除
              articleWithdraw({article_id: arr[index]['article_id']}).then((response:any) => {
                  const result = response.data
                  console.log('articleRemove',result)
                  articleRemove({article_id: arr[index]['article_id']}).then((response:any) => {
                      console.log(`异步操作: ${ arr[index]['article_id']}`, response);
                      setTimeout(() => {
                        executeNext2(index+1)
                      }, 2000)
                  }).catch(() => {
                    setTimeout(() => {
                      executeNext2(index+1)
                    }, 2000)
                  });
              }).catch(() => {
                setTimeout(() => {
                  executeNext2(index+1)
                }, 2000)
              });
            } else {
              articleRemove({article_id: arr[index]['article_id']}).then((response:any) => {
                  console.log(`异步操作: ${ arr[index]['article_id']}`, response);
                  setTimeout(() => {
                    executeNext2(index+1)
                  }, 2000)
              }).catch(() => {
                setTimeout(() => {
                  executeNext2(index+1)
                }, 3000)
              });
            }
          }
          executeNext2(0)
      } else {
        if(page == 2) {
          otherGetData2(idx + 1)
        } else {
          setTimeout(() => {
            onListPulish2(idx, 2)
          }, 2000)
        }
      }
    }).catch(() => {
      otherGetData2(idx + 1)
    })
}
// 判断是否为昨日的时间
const isYesterday = (date) => { 
  // 获取当前日期
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 将时间设置为今天的 00:00:00
  const yesterday = new Date(today);
  yesterday.setDate(yesterday.getDate() - 1); // 设置为昨天的日期
  yesterday.setHours(0, 0, 0, 0); // 将时间重置为昨天的午夜
  const specifiedTime = new Date(date);
  specifiedTime.setHours(specifiedTime.getHours() + specifiedTime.getTimezoneOffset() / 60); // 调整时区
  // date.setHours(0, 0, 0, 0); // 将给定日期的时间也设置为00:00:00，以便比较日期部分
  // return date.getTime() === today.getTime();
  console.log('时间判断：',specifiedTime.toDateString(),yesterday.toDateString(), specifiedTime.toDateString() === yesterday.toDateString())
  return specifiedTime.toDateString() === yesterday.toDateString()
}
// 全选
const onCheckAllChange = (e: any) => {
  let resultData = siteList.value.filter((item1:any) =>item1.pulish_num > 0)
  Object.assign(state, {
    selectedRows: e.target.checked ? resultData : [],
    indeterminate: false,
  });
};
// 监听选中的数据
watch(
  () => state.selectedRows,
  val => {
    let resultData = siteList.value.filter((item1:any) =>item1.pulish_num > 0) // 获取发布数大于0可以选择
    state.indeterminate = !!val.length && val.length < resultData.length;
    state.checkAll = val.length === resultData.length;
  },
);
// 选中事件
const oncheckbox = (data:any) => {
   console.log(data)
}
// 单个选中事件
const onCheckboxClick = (item) => {
  console.log('Checkbox clicked:', item);
};

const menuItems = ref([
  { text: '编辑', action: () => alert('编辑功能') },
]);
const position = ref({ x: 0, y: 0 });
const showContextMenu = (event, site_id) => {
  event.preventDefault();
  siteList.value.forEach((item:any) => {
    if(site_id == item.site_id) {
      item.isVisible = true
    } else {
      item.isVisible = false
    }
  })
  const contextMenuWrapper = event.currentTarget as HTMLElement;
  const rect = contextMenuWrapper.getBoundingClientRect();
  position.value = { x: event.clientX - rect.left, y: event.clientY - rect.top };
  // 在这里调用 ContextMenu 的 showMenu 方法
};

const hideContextMenu = (data:any) => {
  siteList.value.forEach((item:any) => {
    if(data.site_id == item.site_id) {
      item.isVisible = false
    }
  })
  // 在这里调用 ContextMenu 的 hideMenu 方法
};
const hideModel = () => {
  isStop.value = true
  onUserSiteList()
}
onMounted(() => {
  onUserSiteList()
})
watchEffect(() => {

})
//离开界面
onBeforeUnmount(() => {
    // 每次离开当前界面时，清除定时器
    console.log('33243onBeforeUnmount')
    clearTimeout(timer.value)
    timer.value = null
    clearTimeout(timer2.value)
    timer2.value = null
    isStop.value = true
    clearTimeout(timer3.value)
    timer3.value = null
})

// 切换开关
const changeSwitch = (data) => {
    console.log('data', data)
    isStop.value = data.is_stop
}
// 判断是否可以点进列表
const onIsSeeDetails = (data:any) => {
    isSeeDetails.value = data.isSeeDetails
}
// 刷新数据
const pRefreshData = () => {
  isStop.value = true
  state.refreshLoading = true
  otherGetData(0)
}
const publishIsLoading = (data) => {
  state.loading = data.isLoading
}
</script>

<template>
  <div class="home">
    <fullAutomaticPulish :siteList="siteList" :isStop="isStop" :isDefaultCan="isDefaultCan" @change-switch="changeSwitch" @is-see-details="onIsSeeDetails" @p-refresh-data="pRefreshData" @publish-is-loading="publishIsLoading"></fullAutomaticPulish>
    <div style="display: flex;align-items: center;justify-content: space-between;">
      <a-checkbox
        v-model:checked="state.checkAll"
        :indeterminate="state.indeterminate"
        @change="onCheckAllChange"
      >
        全选
      </a-checkbox>
      <publishArticle :selectedRows="state.selectedRows" :refreshLoading="state.refreshLoading" :inspectionLoading="state.inspectionLoading" :isLoding="state.loading" @refresh-data="onDataRefresh" @stop-upload="onPulish" @clear-select-data="onClear" @refresh-list="onRefreshList" @day-inspection-data="dayInspectionData"></publishArticle>
    </div>
    <div>
      <a-spin :spinning="initLoading" wrapperClassName="listCard">
        <div v-if="siteList.length > 0" class="list-s">
          <a-checkbox-group v-model:value="state.selectedRows" @change="oncheckbox" style="width: 100%">
            <a-card :bodyStyle="{  padding: '24px 0' }" class="platform" @contextmenu.prevent="showContextMenu($event, item.site_id)" v-for="(item) in siteList" :key="item.site_id"  @click="onDetails(item.site_id, item.port_config.cookie)">
                <div class="container-site">
                  <a-checkbox :value="item" :disabled="item.pulish_num > 0 ? false : true" class="checkboxs" @click.stop="onCheckboxClick(item)"></a-checkbox>
                  <div class="site-name">{{item.name}}</div>
                  <div style="display: flex;flex-wrap: wrap;">
                    <div class="right-content-module">
                      <div>前日阅读</div>
                      <div>{{ item.read_amount && item.read_amount.length > 0 ? item.read_amount[0].total_pv : '0' }}</div>
                    </div>
                    <!-- <div class="right-content-module">
                      <div>昨日阅读</div> -->
                      <!-- {{ item.read_amount && item.read_amount.length > 0 ? item.read_amount[1].total_pv : '0' }} -->
                      <!-- <div>{{ item.yesterday_view_count ? item.yesterday_view_count : '0' }}</div>
                    </div> -->
                    <div class="right-content-module">
                      <div>总阅读量</div>
                      <div>{{ item.total_view_count ? item.total_view_count : '0' }}</div>
                    </div>
                    <div class="right-content-module">
                      <div>昨日收益</div>
                      <div>{{ item.income && item.income.yesterday_income ? formatNumberToWan(item.income.yesterday_income) : '0' }}</div>
                    </div>
                    <!-- <div class="right-content-module">
                      <div>本周收益</div>
                      <div>{{ item.incomeInfo && item.incomeInfo.week && item.incomeInfo.week.current ? item.incomeInfo.week.current : '0'}}</div>
                    </div> -->
                    <div class="right-content-module">
                      <div>总收益</div>
                      <div>{{ item.income && item.income.total_income ? formatNumberToWan(item.income.total_income) : '0' }}</div>
                    </div>
                    <div class="right-content-module">
                      <div>今日发布</div>
                      <div style="color: #52c41a">{{ item.today_publish_num ?item.today_publish_num : '待统计'}}</div>
                    </div>
                    <div class="right-content-module">
                      <div>剩余发布</div>
                      <div style="color: #52c41a">
                        <a-tooltip :title="item.publish_num_text">
                            <div>
                              {{ item.publish_num_left || 0 }}
                            </div>
                        </a-tooltip>
                      </div>
                    </div>
                    <div class="right-content-module">
                      <div>文章发布时间</div>
                      <div style="color: #52c41a">{{item.prev_time || '-'}}</div>
                    </div>
                    <div class="right-content-module">
                      <div>文章可发布数</div>
                      <div style="color: #52c41a"> {{ item.pulish_num || 0 }}</div>
                    </div>
                    <div class="right-content-module" v-if="item.publishText">
                      <a-tag v-if="item.isPublish" color="geekblue">{{item.publishText}}</a-tag>
                      <span v-else-if="!item.isPublish && item.publishReason">
                        <a-tooltip>
                          <template #title>
                            <span>{{item.publishReason}}</span>
                          </template>
                          <a-tag style="cursor: pointer;" :color="item.errorColor3 ? item.errorColor3 : 'geekblue'">{{item.publishText}}</a-tag>
                        </a-tooltip>
                      </span>
                    </div>
                  </div>
                </div>
                <!-- <div>
                  <a-tag v-if="item.download_status" color="success">{{item.download_status_reason}}</a-tag>
                  <a-tag v-else-if="!item.download_status && item.download_status_reason" color="orange">{{item.download_status_reason}}</a-tag>
                  <a-tag v-if=" item.upload_status" color="blue">完成上传</a-tag>
                  <a-tag v-else-if="!item.isUpload && item.upload_status_reason" color="gold">{{item.upload_status_reason}}</a-tag>
                  <a-tag v-if=" item.list_status" color="default">完成执行</a-tag>
                  <a-tag v-else-if="!item.isUpload && item.list_status_reason" color="gold">{{item.list_status_reason}}</a-tag>
                </div> -->
                <ContextMenu
                  :menuItems="menuItems"
                  :isVisible="item.isVisible"
                  :position="position"
                  :site_id="item.site_id"
                  :name="item.name"
                  @hide-menu="hideContextMenu"
                  @hide-model="hideModel"
                />
            </a-card>
          </a-checkbox-group>
        </div>
        <div style="width: 100%;" v-else>
          <a-empty :image="simpleImage" />
        </div>
      </a-spin>
    </div>
    <div class="pagination">
      <a-pagination  v-model:current="current" v-model:pageSize="pageSize" :total="total" show-less-items @change="onChange" />
    </div>
  </div>
</template>

<style scoped>
.list-s{
    /* display: grid;
    grid-template-columns: 150px 150px 150px 150px 150px;
    grid-column-gap: 20px; */
    display: flex;
    align-items: center;
    align-items: center;
    flex-wrap: wrap;
    padding-top:20px;
    /* margin-left: -5px; */
}
.platform{
  margin-bottom: 20px;
  cursor: pointer;
  /* text-align: center; */
  position: relative;
  /* width: 228px; */
  width:100%;
  /* margin-right: 6px;
  margin-left: 3px; */
  background-color: #2565ad;
  color: #fff;
}
.checkboxs{
  padding: 0 15px;
}
.home-top{
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.logout{
  font-size: 14px;
  cursor: pointer;
}
.pagination{
  margin-top: 20px;
  text-align: right;
}
.container-site{
   display: flex;
   align-items: center;
}
.site-name{
   /* border-right: 1px solid #f0f0f0; */
   /* padding-right: 30px; */
   width: 200px;
}
.right-content-module{
  margin-left: 25px;
  padding-right: 30px;
  margin-top: 8px;
  /* text-align: center; */
}
.right-content-module div:nth-child(2) {
  text-align: center;
}
.listCard{
  width:100%;
}
</style>
